import Vue from "vue";
import VueDraggableResizable from "vue-draggable-resizable";

Vue.component("vue-draggable-resizable", VueDraggableResizable);

export default function (columns, init, initW) {
  const draggingMap = {};
  let actionWidth = 150;
  const actionIndex = columns.findIndex((item) => item.dataIndex === "action");
  const hasAction = actionIndex > -1;
  columns.forEach((col) => {
    draggingMap[col.dataIndex] = col.width;
  });
  if (hasAction) {
    actionWidth = columns[actionIndex].width || actionWidth;
    draggingMap["action"] = actionWidth;
  }
  if (init) {
    const contentW = document.querySelector(".main-content").offsetWidth - 108 - (hasAction ? actionWidth : 0);
    if (initW < contentW) {
      const n = contentW / (columns.length - (hasAction ? 1 : 0));
      columns.forEach((col) => {
        if (col.dataIndex === "action") {
          col.width = actionWidth;
        } else {
          col.width = n;
          draggingMap[col.dataIndex] = col.width;
        }
      });
    }
  }

  const draggingState = Vue.observable(draggingMap);
  const resizeableTitle = (h, props, children) => {
    let thDom = null;
    const { key, ...restProps } = props;
    const col = columns.find((col) => {
      const k = col.dataIndex || col.key;
      return k === key;
    });
    if (!col || !col.width) {
      return <th {...restProps}>{children}</th>;
    }

    const onDrag = (x) => {
      draggingState[key] = 0;
      col.width = Math.max(x, 1);
      return false;
    };

    const onDragstop = () => {
      draggingState[key] = thDom.getBoundingClientRect().width;
      return false;
    };

    return (
      <th {...restProps} v-ant-ref={(r) => (thDom = r)} width={col.width} class="resize-table-th">
        <div class="table-draggable-content" style="padding: 16px">
          {children}
        </div>
        {col.dataIndex !== "action" && (
          <vue-draggable-resizable
            key={col.key}
            class="table-draggable-handle"
            w={10}
            x={draggingState[key] || col.width}
            z={1}
            axis="x"
            draggable={true}
            resizable={false}
            onDragging={onDrag}
            onDragstop={onDragstop}
          />
        )}
      </th>
    );
  };

  return resizeableTitle;
}

export function headerRow() {
  return {
    domProps: {
      id: "sortable_list"
    }
  };
}
